package com.cy.kotlin2test

import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.GlobalScope
import kotlinx.coroutines.asCoroutineDispatcher
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.SharedFlow
import kotlinx.coroutines.flow.flow
import kotlinx.coroutines.flow.flowOn
import kotlinx.coroutines.flow.map
import kotlinx.coroutines.launch
import java.util.concurrent.Executors

class FlowDemo {
    val myDispatcher = Executors.newSingleThreadExecutor().asCoroutineDispatcher()
    private val _stateFlow = MutableStateFlow<Int>(value = 1)
    val stateFlow: SharedFlow<Int> = _stateFlow

    fun testHotFlow(){
        GlobalScope.launch {
            _stateFlow.value = 1 //_stateFlow.emit调用的也是setValue
        }
    }

    fun testCodeFlow(){
        val flow = flow {
            println("emit on ${Thread.currentThread().name}")
            emit("data1")
            kotlinx.coroutines.delay(2000)
            emit("data2")
            kotlinx.coroutines.delay(2000)
            emit("data3")
        }.map {
            println("run first map on ${Thread.currentThread().name}")
            "$it map"
        }.flowOn(Dispatchers.IO)
            .map {
                println("run second map on ${Thread.currentThread().name}")
                "${it},${it.length}"
            }.flowOn(myDispatcher)

        GlobalScope.launch(Dispatchers.Main) {
            println("GlobalScope.launch ${Thread.currentThread().name}")
            flow.collect {
                println("result $it on ${Thread.currentThread().name}")
            }

            println("GlobalScope.launch end ${Thread.currentThread().name}")
        }
    }
}

